package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.GetEntityCmd;
import cn.easyplatform.studio.cmd.entity.PagingCmd;
import cn.easyplatform.studio.cmd.entity.QueryCmd;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.EntityVo;
import cn.easyplatform.studio.vos.QueryResultVo;
import cn.easyplatform.studio.vos.TableCodeLabelVo;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zkmax.zul.Cardlayout;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import java.util.ArrayList;
import java.util.List;

public class TableCodeLabelView extends AbstractView<TableCodeLabelVo> {
    private TableCodeLabelVo vo;
    private List<EntityVo> entityVos = new ArrayList<>();
    private TableBean selectedTableBean;

    private Cardlayout cardlayout;
    private Listbox contentListbox;
    private Textbox searchTextbox;
    private Paging paging;
    private Label selectedLabel;
    private Label tableNameLabel;
    private Combobox codeCombobox;
    private Combobox labelCombobox;

    protected TableCodeLabelView(Component component, EditorCallback<TableCodeLabelVo> cb) {
        super(component, cb);
        if (cb != null) {
            vo = cb.getValue();
        }
    }

    @Override
    protected void createContent(Component parent) {
        cardlayout = new Cardlayout();
        cardlayout.setHflex("1");
        cardlayout.setVflex("1");
        parent.appendChild(cardlayout);

        Vlayout vlayout = new Vlayout();
        vlayout.setHflex("1");
        vlayout.setVflex("1");
        cardlayout.appendChild(vlayout);

        selectedLabel = new Label();
        selectedLabel.setHflex("1");
        selectedLabel.setValue(choose());
        selectedLabel.setStyle("font-size: 18px;");
        vlayout.appendChild(selectedLabel);

        Hlayout searchHlayout = new Hlayout();
        searchHlayout.setHeight("24px");
        searchHlayout.setHflex("1");
        searchHlayout.setSpacing("0px");
        searchHlayout.setSclass("ui-functionBar-searchBar ui-div-center-parent");
        vlayout.appendChild(searchHlayout);
        A searchA = new A();
        searchA.setSclass("icon font_family icon-canshu-sousuo ui-button-a");
        searchA.setStyle("border: none;outline: none;");
        searchHlayout.appendChild(searchA);
        searchTextbox = new Textbox();
        searchTextbox.setHflex("1");
        searchTextbox.setHeight("24px");
        searchTextbox.setPlaceholder(Labels.getLabel("navi.search.completion.placeholder"));
        searchTextbox.setStyle("border: none;");
        searchTextbox.setSclass("ui-textbox-shadow");
        searchHlayout.appendChild(searchTextbox);

        contentListbox = new Listbox();
        contentListbox.setHflex("1");
        contentListbox.setVflex("1");
        contentListbox.setStyle("background: #ffffff0a;");
        vlayout.appendChild(contentListbox);
        Listhead listhead = new Listhead();
        listhead.setSizable(true);
        contentListbox.appendChild(listhead);
        String[] nameList = new String[]{Labels.getLabel("entity.id"), Labels.getLabel("entity.name"),
                Labels.getLabel("entity.desp")};
        for (String name : nameList) {
            Listheader listheader = new Listheader(name);
            listheader.setHflex("1");
            contentListbox.getListhead().appendChild(listheader);
        }

        paging = new Paging();
        paging.setPageSize(30);
        paging.setHflex("1");
        paging.setStyle("background: #ffffff0a;text-align: center;");
        paging.addEventListener(ZulEvents.ON_PAGING, this);
        vlayout.appendChild(paging);
        search();

        Div buttonDiv = new Div();
        buttonDiv.setHflex("1");
        buttonDiv.setHeight("50px");
        buttonDiv.setStyle("background: white;");
        vlayout.appendChild(buttonDiv);

        //entity.api.clear
        Button clearBtn = new Button(Labels.getLabel("entity.api.clear"));
        clearBtn.setStyle("left: 20px;position: absolute;margin-top: 13px;");
        clearBtn.setId("tableCodeLabel_button_clear");
        clearBtn.addEventListener(Events.ON_CLICK, this);
        buttonDiv.appendChild(clearBtn);

        Button nextBtn = new Button(Labels.getLabel("button.next"));
        nextBtn.setStyle("right: 20px;position: absolute;margin-top: 13px;");
        nextBtn.setId("tableCodeLabel_button_next");
        nextBtn.addEventListener(Events.ON_CLICK, this);
        buttonDiv.appendChild(nextBtn);

        //第二个页面
        Vlayout secondVlayout = new Vlayout();
        secondVlayout.setVflex("1");
        secondVlayout.setHflex("1");
        cardlayout.appendChild(secondVlayout);

        Grid grid = new Grid();
        grid.setHflex("1");
        grid.setVflex("1");
        grid.setSclass("noborder");
        grid.setOddRowSclass("none");
        secondVlayout.appendChild(grid);
        Columns columns = new Columns();
        columns.appendChild(new Column());
        columns.appendChild(new Column());
        grid.appendChild(columns);
        Rows rows = new Rows();
        grid.appendChild(rows);
        Row tableRow = new Row();
        rows.appendChild(tableRow);
        Label tableLabel = new Label(Labels.getLabel("entity.table") + ":");
        tableRow.appendChild(tableLabel);
        tableNameLabel = new Label();
        tableRow.appendChild(tableNameLabel);
        Row codeRow = new Row();
        rows.appendChild(codeRow);
        Label codeLabel = new Label(Labels.getLabel("menu.code") + ":");
        codeRow.appendChild(codeLabel);
        codeCombobox = new Combobox();
        codeCombobox.addEventListener(Events.ON_CHANGE, this);
        codeCombobox.setReadonly(true);
        codeRow.appendChild(codeCombobox);
        Row labelRow = new Row();
        rows.appendChild(labelRow);
        Label labelLabel = new Label(Labels.getLabel("entity.table.label") + ":");
        labelRow.appendChild(labelLabel);
        labelCombobox = new Combobox();
        labelCombobox.addEventListener(Events.ON_CHANGE, this);
        labelCombobox.setReadonly(true);
        labelRow.appendChild(labelCombobox);

        Div secondButtonDiv = new Div();
        secondButtonDiv.setHflex("1");
        secondButtonDiv.setHeight("50px");
        secondButtonDiv.setStyle("background: white;");
        secondVlayout.appendChild(secondButtonDiv);

        Button backBtn = new Button(Labels.getLabel("button.back"));
        backBtn.setStyle("left: 20px;position: absolute;margin-top: 13px;");
        backBtn.setId("tableCodeLabel_button_back");
        backBtn.addEventListener(Events.ON_CLICK, this);
        secondButtonDiv.appendChild(backBtn);

        Button okBtn = new Button(Labels.getLabel("button.ok"));
        okBtn.setStyle("right: 20px;position: absolute;margin-top: 13px;");
        okBtn.setId("tableCodeLabel_button_ok");
        okBtn.addEventListener(Events.ON_CLICK, this);
        secondButtonDiv.appendChild(okBtn);
    }

    private void createContentListbox() {
        contentListbox.getItems().clear();
        for (EntityVo vo : entityVos) {
            Listitem row = new Listitem();
            row.setValue(vo);
            row.appendChild(new Listcell(vo.getId()));
            row.appendChild(new Listcell(vo.getName()));
            row.appendChild(new Listcell(vo.getDesp()));
            row.setParent(contentListbox);
            row.addEventListener(Events.ON_CLICK, this);
        }
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(paging)) {// 分页
            PagingEvent pe = (PagingEvent) event;
            int pageNo = pe.getActivePage() + 1;
            String field = null;
            if (event.getTarget().equals(paging)) {
                if (!Strings.isBlank(searchTextbox.getValue()))
                    field = "*";
                entityVos = StudioApp.execute(paging,
                        new PagingCmd("Table", field, searchTextbox.getValue()
                                .trim(), paging.getPageSize(), pageNo));
                createContentListbox();
            }
        } else if (event.getTarget().equals(searchTextbox) && event.getName().equals(Events.ON_OK)) {
            if (event instanceof OpenEvent) {
                OpenEvent evt = (OpenEvent) event;
                String val = (String) evt.getValue();
                ((Textbox) event.getTarget()).setValue(val);
            }
            search();
        } else if (event.getTarget() instanceof Listitem) {
            Listitem selectedItem = (Listitem)event.getTarget();
            EntityVo selectedVo = selectedItem.getValue();// 打开参数
            if (vo == null)
                vo = new TableCodeLabelVo();
            vo.setTableName(selectedVo.getId());
            vo.setCodeName("");
            vo.setLabelName("");
            selectedLabel.setValue(choose());
        } else if ("tableCodeLabel_button_next".equals(event.getTarget().getId())) {
            if (vo != null && Strings.isBlank(vo.getTableName()) == false) {
                cardlayout.next();
                tableNameLabel.setValue(vo.getTableName());
                selectedTableBean = (TableBean) StudioApp.execute(new GetEntityCmd(vo.getTableName()));
                combobox();
            } else {
                WebUtils.showInfo(Labels.getLabel("sqlwizard.error.noChooseTable"));
            }
        } else if ("tableCodeLabel_button_back".equals(event.getTarget().getId())) {
            cardlayout.previous();
            selectedLabel.setValue(choose());
        } else if (codeCombobox.equals(event.getTarget())) {
            if (vo == null) {
                vo = new TableCodeLabelVo();
                vo.setTableName(selectedTableBean.getName());
            }
            vo.setCodeName((String) codeCombobox.getSelectedItem().getValue());
        } else if (labelCombobox.equals(event.getTarget())) {
            if (vo == null) {
                vo = new TableCodeLabelVo();
                vo.setTableName(selectedTableBean.getName());
            }
            vo.setLabelName((String) labelCombobox.getSelectedItem().getValue());
        } else if ("tableCodeLabel_button_ok".equals(event.getTarget().getId())) {
            if (vo != null && Strings.isBlank(vo.getTableName()) == false &&
                    Strings.isBlank(vo.getCodeName()) == false && Strings.isBlank(vo.getLabelName()) == false) {
                cardlayout.getRoot().detach();
                onCloseClick(win);
                if (cb != null)
                    cb.setValue(vo);
            } else {
                WebUtils.showInfo(Labels.getLabel("sqlwizard.error.noChooseField"));
            }
        } else if ("tableCodeLabel_button_clear".equals(event.getTarget().getId())) {
            vo = new TableCodeLabelVo();
            cardlayout.getRoot().detach();
            onCloseClick(win);
            if (cb != null)
                cb.setValue(vo);
        }
    }

    private void search() {
        QueryResultVo result = null;
        if (Strings.isBlank(searchTextbox.getValue())) {
            result = StudioApp.execute(contentListbox, new QueryCmd("Table",
                    paging.getPageSize()));
        } else {
            result = StudioApp.execute(contentListbox, new QueryCmd("Table", "*",
                    searchTextbox.getValue().trim(), paging.getPageSize()));
        }
        paging.setTotalSize(result.getTotalSize());
        paging.setActivePage(0);
        entityVos = result.getEntities();
        createContentListbox();
    }

    private String choose() {
        StringBuffer sb = new StringBuffer();
        sb.append(Labels.getLabel("entity.table.selected")).append(":");
        if (vo != null) {
            if (Strings.isBlank(vo.getTableName()) == false) {
                sb.append(vo.getTableName());
            } else {
                sb.append(Labels.getLabel("entity.table.unSelected"));
            }
            sb.append("(").append(Labels.getLabel("entity.table")).append("),");
            if (Strings.isBlank(vo.getCodeName()) == false) {
                sb.append(vo.getCodeName());
            } else {
                sb.append(Labels.getLabel("entity.table.unSelected"));
            }
            sb.append("(").append(Labels.getLabel("menu.code")).append("),");
            if (Strings.isBlank(vo.getLabelName()) == false) {
                sb.append(vo.getLabelName());
            } else {
                sb.append(Labels.getLabel("entity.table.unSelected"));
            }
            sb.append("(").append(Labels.getLabel("entity.table.label")).append(")");
        }
        return sb.toString();
    }

    private void combobox() {
        codeCombobox.getItems().clear();
        labelCombobox.getItems().clear();
        if (selectedTableBean != null) {
            for (TableField tableField : selectedTableBean.getFields()) {
                Combobox[] comboboxes = new Combobox[]{codeCombobox, labelCombobox};
                String[] names = new String[]{vo.getCodeName(), vo.getLabelName()};
                for (int i = 0; i < comboboxes.length; i++) {
                    Comboitem comboitem = new Comboitem(tableField.getName());
                    comboitem.setParent(comboboxes[i]);
                    comboitem.setValue(tableField.getName());
                    if (Strings.isBlank(names[i]) == false) {
                        if (names[i].equals(tableField.getName()))
                            comboboxes[i].setSelectedItem(comboitem);
                    }
                }
            }
        }
    }
}
